package com.peaksport.pkms.learn.day21.consumer.controller;

import java.util.concurrent.CompletableFuture;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import org.apache.servicecomb.provider.pojo.RpcReference;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.apache.servicecomb.provider.springmvc.reference.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.peaksport.pkms.learn.day21.consumer.vo.Person;
import com.peaksport.pkms.learn.day21.helloworld.vo.GreetingResponse;

@RestSchema(schemaId="helloConsumer")
@Path("helloworld-consumer/v0")
public class HelloConsumerService {
	
	@RpcReference(microserviceName="helloworld-provider",schemaId="helloworldProvider")
	private HelloTestService helloTestService;
	@RpcReference(microserviceName="helloworld-provider",schemaId="helloworld1")
	private HelloTestService helloTestService2;
	@RpcReference(microserviceName="helloworld-provider",schemaId="helloworldProvider")
	private HelloServiceReactive helloReactive;
	
	
	private RestTemplate restTemplate = RestTemplateBuilder.create();
	
	@Path("/hello")
	@GET
	public String sayHello(@QueryParam("name") String name) {
		return helloTestService.sayHello(name);
		
	}
	
	@Path("/hello2")
	@GET
	public String sayHello2(@QueryParam("name") String name) {
		return helloTestService2.sayHello1(name);
	}
	@Path("/hellReactive")
	@GET
	public CompletableFuture<String> sayHelloReactive(@QueryParam("name") String name) {
		return helloReactive.sayHello(name).whenComplete((result,exc) -> {
			if (exc == null)
				System.out.println("aaaa");
			else {
				System.out.println("============1============");
				System.out.println(exc.getMessage());
				System.out.println("============2============");
			}
		});
	}
	
	@Path("/helloRT")
	@GET
	public String sayHelloRT(@QueryParam("name") String name ) {
		ResponseEntity<String> responseEntity = restTemplate.getForEntity("cse://helloworld-provider/provider/v0/hello?name="+name, String.class);
		return responseEntity.getBody();
	}
	
	@Path("/greeting")
	@POST
	public GreetingResponse greeting(Person person) {
		return helloTestService.greeting(person);
	}
	
	@Path("/greetingRT")
	@POST
	public GreetingResponse greetingRT(Person person) {
		ResponseEntity<GreetingResponse> responseEntity = restTemplate.postForEntity("cse://helloworld-provider/provider/v0/greeting", person,GreetingResponse.class);
		return responseEntity.getBody();
	}
	
}
